from certificate_manager.models import *
from certificate_manager.serializers import *
from django.http import HttpResponseForbidden
from django.shortcuts import render
from rest_framework import permissions
from rest_framework import status
from rest_framework import viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.exceptions import NotFound, NotAcceptable

class UserViewSet(viewsets.ModelViewSet):
        queryset = User.objects.all()
        serializer_class = UserSerializer

        def update(self, request, pk=None):
                # 现在我们检查一下字段是否正确
                login_user = request.user
                update_uesr = request.data
                if login_user.uid == update_uesr['uid']:
                        return super().update(request, pk)
                else:
                        return Response({ 'msg': 'You bad guy ;)' }, status=status.HTTP_406_NOT_ACCEPTABLE)

        def retrieve(self, request, pk=None):
            try:
                user = User.objects.get(uid=pk)
            except:
                raise NotFound('user not found by uid')
            return Response(UserSerializer(user).data)

        def get_permissions(self):
                if self.action == 'create':
                        # 允许任何用户创建User对象
                        permission_classes = [permissions.AllowAny]
                elif self.action in ['retrieve', 'update']:
                        permission_classes = [permissions.IsAuthenticated]
                else:
                        permission_classes = [permissions.IsAdminUser]
                return [permission() for permission in permission_classes]
